import { router } from '@/router'
import type { RouteRecordRaw } from 'vue-router'
import { userStore } from '@/store/modules/user'
import { permissionStore } from '@/store/modules/permission'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

NProgress.configure({
  showSpinner: false // 是否显示加载ico
})

// 页面白名单列表
const whiteList = ['/login']

const getPageTitle = (pageName: string, commonTitleHide = false) => {
  const title = '标普云SAAS管理平台'
  if (pageName) {
    return commonTitleHide ? `${pageName}` : `${pageName} - ${title}`
  }
  return title
}

router.beforeEach(async (to, from, next) => {
  NProgress.start()
  const userModule = userStore()
  const permissionModule = permissionStore()
  if (userModule.token) {
    // 用户已经登录,如果跳到login页面，则直接回到/
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      // 否者，先获取用户的permission权限点
      if (!userModule.hasCachePermission) {
        try {
          await userModule.getUserInfo()
          await userModule.getMenu()
          permissionModule.generateRoutes(userModule.routesMapList)
          permissionModule.dynamicRoutes.forEach((route) => {
            router.addRoute(route as unknown as RouteRecordRaw)
          })
          await userModule.inquiryPermissionctionList()
          // 获取角色权限列表
          // userModule.getRoleAuthList()
          // 解决vue-router4 addRoute找不到路由问题
          // if (!to.matched.length) {
          //   router.replace(to.path)
          // }
          next({ ...to, replace: true })
        } catch (err) {
          // Remove token and redirect to login page
          userModule.resetToken()
          let timestamp = new Date().getTime()
          next(`/login?redirect=${to.path}&timestamp=${timestamp}`)
          NProgress.done()
        }
      } else {
        // 有权限直接下一步
        next()
      }
    }
  } else {
    // 用户没有登录，先查看是否在白名单
    if (whiteList.indexOf(to.path) !== -1) {
      // 如果在白名单里面则继续
      next()
    } else {
      // 否者重定向到登录页
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach((to) => {
  NProgress.done()
  document.title = getPageTitle(to.meta?.title as string, to.meta?.commonTitleHide as boolean)
})
